package jp.dodododo.dao.sql.node;

import java.util.HashMap;
import java.util.Map;

import jp.dodododo.dao.context.CommandContext;
import jp.dodododo.dao.dialect.Dialect;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * @author Satoshi Kimura
 */
public class BindVariableNode extends AbstractNode {

	private String expression;

	private String[] names;

	public BindVariableNode(String expression) {
		this.expression = expression;
		names = StringUtils.split(expression, ".");
	}

	public void accept(CommandContext ctx) {
		String name = names[0];
		Object value = ctx.getArg(name);

		if (value != null && 1 < names.length) {
			Map<String, Object> root = new HashMap<String, Object>();
			root.put(name, value);
			Dialect dialect = ctx.getDialect();
			value = getValue(expression, names, root, dialect);
		}
		int type;
		if (expression.equals(name)) {
			type = ctx.getArgType(name);
		} else {
			type = getType(value);
		}
		ctx.addSql("?", value, type);
	}
}
